﻿/****************************************************************
*   作者：corer
*   创建时间：2018/3/3 16:12:30
*   描述说明：
*****************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;

namespace Model
{
  public class FSMMachine<T> where T : FSMAIControl
  {
    private Dictionary<Type, IFSMState<T>> states = new Dictionary<Type, IFSMState<T>>();

    public IFSMState<T> CurrentState { get; private set; }

    private IFSMState<T> callEnter;

    private T ai;

    public void Init(T ai,IFSMState<T> defaultState)
    {
      this.ai = ai;
      this.CurrentState = defaultState;
    }

    public IFSMState<T> Add<S>()
    {
      return this.Add(typeof(S));
    }

    public void SetCurrentState(IFSMState<T> state)
    {
      this.CurrentState = state;
    }

    public IFSMState<T> Add(Type type)
    {
      IFSMState<T> state;
      if (!states.TryGetValue(type, out state))
      {
        state = Activator.CreateInstance(type) as IFSMState<T>;
        states.Add(type, state);
        state.Init(ai);
      }
      callEnter = state;
      return state;
    }

    public void Update()
    {
      if (callEnter != null)
      {
        callEnter.Enter(ai);
        callEnter = null;
      }

      if (CurrentState != null)
      {
        Type type = CurrentState.CheckTransition(ai);
        if (type != null)
        {
          CurrentState.Exit(ai);
          IFSMState<T> state = this.Add(type);
          CurrentState = state;
          return;
        }
        CurrentState.Update(ai);
      }
    }
  }
}